#include "player.h"

#include <common/log/log.h>
#include <common/net/message_parse.h>
#include <common/net/session.h>
#include <common/utils/util.h>

#include <common.pb.h>
#include <tables.pb.h>

#include "base/sub_server_mgr.h"
#include "base/db_mgr.h"

Player::Player(uint32_t playerID)
    : isOnline_(false)
{
    player_.set_player_id(playerID);
}


bool Player::init()
{
    auto dbMgr = ServerMgr::get().getSubServ<SubServerMgr>()->getSubMgr<DBMgr>(eDB);
    if (!dbMgr)
    {
        LOG_ERROR("DB Manager not init.");
        return false;
    }
    return initProtoDataFromDb(dbMgr->getMysqlConn(), &player_);
}


bool Player::sendMsg(const MessageID& msgID, google::protobuf::Message& msg)
{
    if (!lgSession_)
    {
        LOG_ERROR("Player send msg, but lg session is null. msg id:" << std::hex << msgID.msgID );
        return false;
    }
    proto::common::CommonGateRet ret;
    ret.set_player_id(getID());
    ret.set_msg_id(msgID.msgID);
    const std::string buf = msg.SerializeAsString();
    ret.set_msg(buf);
    ret.set_msg_len(buf.size());
    lgSession_->sendMsg(proto::common::eCommon, proto::common::S2C_COMMON_GATE_RET, ret);
    return true;
}

bool Player::sendMsg(uint16_t moduleType, uint16_t msgID, google::protobuf::Message& msg)
{
    if (!lgSession_)
    {
        LOG_ERROR("login gate session not set.");
        return false;
    }
    return sendMsg(MessageID(moduleType, msgID), msg);
}


bool Player::onLogin()
{
    isOnline_ = true;
    LOG_DEBUG("Player (" << player_.player_name() << "," << player_.player_id() << ") login.");
    return true;
}

bool Player::onLogout()
{
    isOnline_ = false;
    LOG_DEBUG("Player (" << player_.player_name() << "," << player_.player_id() << ") logout.");
    return true;
}
